<template>
  <!-- 操作按钮 -->
  <div class="flex justify-between mb-3">
    <div>
      <el-button class="mb-15px" type="warning" :icon="Refresh" @click="getList"> 刷新 </el-button>
      <el-button class="mb-15px" type="success" :icon="Document" :disabled="disabled" @click="onSave"> 保存 </el-button>
      <el-button class="mb-15px" type="primary" :icon="Edit" :disabled="disabled" @click="onSubmit"> 提交 </el-button>
    </div>
    <div>
      <el-button class="mb-15px" type="warning" :icon="RefreshLeft" @click="revoke">
        撤销
      </el-button>
      <el-button class="mb-15px" type="success" :icon="Edit" @click="check"> 审核 </el-button>
      <el-button class="mb-15px" type="primary" :icon="EditPen" @click="unCheck">
        反审核
      </el-button>
      <el-button class="mb-15px" type="danger" :icon="FolderDelete" @click="valid">
        作废
      </el-button>
    </div>
  </div>

  <!-- 表头 -->
  <DetailHeadTable ref="headTable" :partParams="data" :column="headColumn" :list="headList" />
  <!-- 列表 -->
  <DetailTable
    class="mt-3"
    ref="table"
    :partParams="data"
    :column="column"
    :list="list"
    @get-tab-info="getTabInfo"
  />
  <!-- 检验结果|缺陷记录|检验项目|整体抽样 Tab -->
  <DetailTab ref="detailTab" :partParams="data" :tabInfo="detailTabInfo" />
</template>

<script lang="ts" setup>
import {
  Refresh,
  Document,
  Edit,
  RefreshLeft,
  EditPen,
  FolderDelete
} from '@element-plus/icons-vue'
import { objectToQueryParams } from '@/utils/objectToQuery'
import { computed, defineProps, onBeforeUnmount, ref } from 'vue'
import * as BasicApi from '@/api'

import DetailHeadTable from './DetailHeadTable.vue'
import DetailTable from './DetailTable.vue'
import DetailTab from './DetailTab.vue'
import { useMessage } from '@/hooks/useMessage'
import eventBus from '@/libs/eventBus'
const message = useMessage()

//定义接收的props
const props = defineProps({
  // 定义一个对象类型的 prop
  data: {
    type: Object,
    default: () => ({ groupName: '', jobType: '' })
  }
})

const jobType = computed(() => {
  return props.data.jobType
})

const disabled = ref(false)
const setButtonStatus = (flag: boolean)=>{
  disabled.value = flag
}
//接收保存和提交按钮是否置灰的事件
eventBus.on(`IR1ButtonDisabled-${jobType.value}`, setButtonStatus)

const emit = defineEmits(['refresh'])

//表头信息
const headColumn = ref<any[]>([])
const headList = ref<any[]>([])
//列表信息
const column = ref<any[]>([])
const list = ref<any[]>([])

const getDetailField = (data: any) => {
  console.log(`output->data`, data)
  const {
    detailHeadFieldInfo,
    detailFieldInfo,
    policyFieldInfo,
    defectFieldInfo,
    inspectFieldInfo,
    samplingFieldInfo
  } = data
  headColumn.value = detailHeadFieldInfo ?? []
  column.value = detailFieldInfo ?? []
  detailTabInfo.value.policyFieldInfo = policyFieldInfo ?? []
  detailTabInfo.value.defectFieldInfo = defectFieldInfo ?? []
  detailTabInfo.value.inspectFieldInfo = inspectFieldInfo ?? []
  detailTabInfo.value.samplingFieldInfo = samplingFieldInfo ?? []
}
//渲染列头
eventBus.on(`getDetailField-${jobType.value}`, getDetailField)

const loading = ref(false)
const getList = async () => {
  loading.value = true
  try {
    const post = {
      groupName: props.data.groupName,
      jobType: props.data.jobType,
      operType: 'GetDetail'
    }
    const inputStr = objectToQueryParams(post)
    //获取行数据
    const rowData = sessionStorage.getItem('WMS_IR1_ROW_DATA') as string
    const jsonData = JSON.parse(rowData) ?? {}
    const result = (await BasicApi.Query({ inputStr, jsonData })) as any
    const { code, msg, data, rsCount } = result
    if (code !== 200) {
      message.error(msg)
      return
    }
    headList.value = data.headInfo ?? []
    list.value = data.listInfo ?? []
  } finally {
    loading.value = false
  }
}

const resetTab = () => {
  //每次进来都要重新清空当前行和列表数据
  detailTabInfo.value.currentRow = {}
  detailTabInfo.value.policyInfo = []
  detailTabInfo.value.defectInfo = []
  detailTabInfo.value.inspectInfo = []
  detailTabInfo.value.samplingInfo = []
}

const render = () => {
  resetTab()
  getList()
}

//渲染列表
eventBus.on(`getDetailList-${jobType.value}`, render)

//4个Tab
const detailTabInfo = ref({
  //当前行数据
  currentRow: {},
  // 检验结果
  policyFieldInfo: [],
  policyInfo: [],
  // 缺陷记录
  defectFieldInfo: [],
  defectInfo: [],
  // 检验项目
  inspectFieldInfo: [],
  inspectInfo: [],
  // 整体抽样
  samplingFieldInfo: [],
  samplingInfo: []
})
//获取4个Tab详情
const getTabInfo = async (current: any) => {
  detailTabInfo.value.currentRow = current
  console.log(`output->当前行数据`, current)
  const post = {
    groupName: props.data.groupName,
    jobType: props.data.jobType,
    operType: 'GetIRInfo'
  }
  const inputStr = objectToQueryParams(post)
  const jsonData = {
    headInfo: headList.value,
    listInfo: [current]
  }
  const result = (await BasicApi.Query({ inputStr, jsonData })) as any
  const { code, msg, data, rsCount } = result
  if (code !== 200) {
    message.error(msg)
    return
  }
  const {
    policyInfo: policyList,
    defectInfo: defectList,
    inspectInfo: inspectList,
    samplingInfo: sampleList
  } = data
  detailTabInfo.value.policyInfo = policyList ?? []
  detailTabInfo.value.defectInfo = defectList ?? []
  detailTabInfo.value.inspectInfo = inspectList ?? []
  detailTabInfo.value.samplingInfo = sampleList ?? []
}

const onSave = async () => {
  // 校验表单
  try {
    const inputStr = objectToQueryParams({
      groupName: props.data.groupName,
      jobType: props.data.jobType,
      operType: 'Save'
    })
    const currentRowLen = Object.keys(detailTabInfo.value.currentRow).length
    const post = {
      inputStr,
      jsonData: {
        headInfo: headList.value,
        listInfo: currentRowLen ? [detailTabInfo.value.currentRow] : list.value,
        policyInfo: detailTabInfo.value.policyInfo,
        defectInfo: detailTabInfo.value.defectInfo
      }
    }
    const res = (await BasicApi.Save(post)) as any
    if (res.code !== 200) {
      message.error(res.msg)
      return
    }
    message.success(res.msg)
    //刷新当前页面的表格
    getList()
    currentRowLen && getTabInfo(detailTabInfo.value.currentRow)
  } finally {
    console.log('')
  }
}
const onSubmit = async () => {
  try {
    const inputStr = objectToQueryParams({
      groupName: props.data.groupName,
      jobType: props.data.jobType,
      operType: 'Submit'
    })
    const currentRowLen = Object.keys(detailTabInfo.value.currentRow).length
    const post = {
      inputStr,
      jsonData: {
        headInfo: headList.value,
        listInfo: currentRowLen ? [detailTabInfo.value.currentRow] : list.value,
        policyInfo: detailTabInfo.value.policyInfo,
        defectInfo: detailTabInfo.value.defectInfo
      }
    }
    const res = (await BasicApi.Submit(post)) as any
    if (res.code !== 200) {
      message.error(res.msg)
      return
    }
    message.success(res.msg)
    //刷新当前页面的表格
    getList()
    currentRowLen && getTabInfo(detailTabInfo.value.currentRow)
  } finally {
    console.log('')
  }
}

/** 撤销操作 */
const revoke = async () => {
  try {
    // 更新的二次确认
    await message.delConfirm('请确认是否撤销？')
    // 发起更新
    const inputStr = objectToQueryParams({
      groupName: props.data.groupName,
      jobType: props.data.jobType,
      operType: 'CancelAssign'
    })
    const post = {
      inputStr,
      jsonData: {
        headInfo: headList.value,
        listInfo: list.value
      }
    }
    const res = (await BasicApi.WorkFlowOper(post)) as any
    if (res.code !== 200) {
      message.error(res.msg)
      return
    }
    message.success(res.msg)
    // 刷新列表
    getList()
  } catch {}
}

/** 审核操作 */
const check = async () => {
  try {
    // 更新的二次确认
    await message.delConfirm('请确认是否审核？')
    // 发起更新
    const inputStr = objectToQueryParams({
      groupName: props.data.groupName,
      jobType: props.data.jobType,
      operType: 'Audit'
    })
    const post = {
      inputStr,
      jsonData: {
        headInfo: headList.value,
        listInfo: list.value
      }
    }
    const res = (await BasicApi.WorkFlowOper(post)) as any
    if (res.code !== 200) {
      message.error(res.msg)
      return
    }
    message.success(res.msg)
    // 刷新列表
    getList()
  } catch {}
}

/** 反审核操作 */
const unCheck = async () => {
  try {
    // 更新的二次确认
    await message.delConfirm('请确认是否反审核？')
    // 发起更新
    const inputStr = objectToQueryParams({
      groupName: props.data.groupName,
      jobType: props.data.jobType,
      operType: 'UnAudit'
    })
    const post = {
      inputStr,
      jsonData: {
        headInfo: headList.value,
        listInfo: list.value
      }
    }
    const res = (await BasicApi.WorkFlowOper(post)) as any
    if (res.code !== 200) {
      message.error(res.msg)
      return
    }
    message.success(res.msg)
    // 刷新列表
    getList()
  } catch {}
}

/** 作废操作 */
const valid = async () => {
  try {
    // 更新的二次确认
    await message.delConfirm('请确认是否作废？')
    // 发起更新
    const inputStr = objectToQueryParams({
      groupName: props.data.groupName,
      jobType: props.data.jobType,
      operType: 'Cancel'
    })
    const post = {
      inputStr,
      jsonData: {
        headInfo: headList.value,
        listInfo: list.value
      }
    }
    const res = (await BasicApi.WorkFlowOper(post)) as any
    if (res.code !== 200) {
      message.error(res.msg)
      return
    }
    message.success(res.msg)
    // 刷新列表
    getList()
  } catch {}
}

// 在组件卸载之前移除侦听
onBeforeUnmount(() => {
  eventBus.off(`getDetailField-${jobType.value}`, getDetailField)
  eventBus.off(`getDetailList-${jobType.value}`, getList)
})
</script>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
